package model;

import java.sql.SQLException;

public class Account extends BaseModel {
	private static PasswordHasher ph;

	private String username;
	private String password;
	private WorkSharedDB db;

	public Account(String username, String password) throws Exception {
		super();
		setUsername(username);
		setPassword(password);
		this.db = new WorkSharedDB();
		if (ph == null) {
			ph = new PasswordHasher();
		}
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	String getPassHash() {
		return ph.toHash(this.password);
	}

	public void setUsername(String username) throws Exception {
		doStringCheck(username, "Username", 40);
		this.username = username;
	}

	public void setPassword(String password) throws Exception {
		if (password.length() > 3) {
			this.password = password;
		} else {
			throw new Exception("O password precisa possuir pelo menos 4 caracteres.");
		}
	}

	public boolean login() throws Exception {
		try {
			db.statement = WorkSharedDB.connection
					.prepareStatement("SELECT * FROM authors WHERE username = ? AND passhash = ?");
			db.statement.setString(1, getUsername());
			db.statement.setString(2, getPassHash());

			// Se houver uma linha, encontrou a conta do autor
			return db.statement.executeQuery().next();

		} catch (SQLException sqlEx) {
			throw new Exception(sqlEx.getMessage());
		}
	}

}
